package com.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@CrossOrigin("*")
public class UploadController {

    private String tmp="F:/tmp";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/upload")
    public String upload(MultipartFile file) throws IOException{
        System.out.println("来了");

        //得到原来的文件夹
        String oldFileName=file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index=oldFileName.lastIndexOf(".");
        //得到后缀名
        String extName=oldFileName.substring(index);
        //新的文件名
        String newFileName=System.currentTimeMillis()+extName;
        //传到tmp 目录
        File descFile=new File(tmp,newFileName);
        file.transferTo(descFile);

        //微信服务器识别
        String url="https://api.weixin.qq.com/cv/ocr/bankcard?type=MODE&access_token=%s";
//        String url="https://api.weixin.qq.com/cv/ocr/bankcard?access_token=%s";

        String ACCESS_TOCKEN=(String)redisTemplate.boundValueOps("token").get();
        System.out.println("ACCESS_TOCKEN"+ACCESS_TOCKEN);
        String newUrl=String.format(url,ACCESS_TOCKEN);
        System.out.println("newUrl"+newUrl);

        //请求的url,上传的对象，返回的结果类型
        FileSystemResource str=new FileSystemResource(descFile);
        MultiValueMap request=new LinkedMultiValueMap();
        request.add("file",str);
        String result=restTemplate.postForObject(newUrl,request,String.class);
        String number= JSONObject.parseObject(result).getString("number");
        return number;

    }

}
